package com.castle.fortress.admin.argFlow.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.castle.fortress.admin.argFlow.constants.RAGFlowApiConstants;
import com.castle.fortress.admin.argFlow.dto.*;
import com.castle.fortress.admin.argFlow.service.RAGFlowService;
import com.castle.fortress.admin.system.entity.ConfigParamsEntity;
import com.castle.fortress.admin.system.service.ConfigParamsService;
import com.castle.fortress.common.entity.RespBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
import java.net.URI;

import com.castle.fortress.admin.argFlow.exception.FileUploadException;
import com.castle.fortress.admin.argFlow.utils.FileUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpResponse;

/**
 * RAGFlow服务实现类
 */
@Slf4j
@Service
public class RAGFlowServiceImpl implements RAGFlowService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ConfigParamsService configParamsService;

    public static String ragflowApiUrl = null;
    public static String apiKey = null;


    @Value("${ragflow.upload.max-size:50}")
    private long maxUploadSizeMB;


    @PostConstruct
    public void init() {
        // 初始化代码，从配置表获取API地址和API密钥
        // 获取API URL
        QueryWrapper<ConfigParamsEntity> urlWrapper = new QueryWrapper<>();
        urlWrapper.eq("param_code", "ragflowApiUrl");
        urlWrapper.last("limit 1");
        ConfigParamsEntity urlEntity = configParamsService.getOne(urlWrapper);
        if (urlEntity != null && StrUtil.isNotEmpty(urlEntity.getParamValue())) {
            ragflowApiUrl = urlEntity.getParamValue();
            log.info("从配置表加载API地址: {}", ragflowApiUrl);
        } else {
            log.warn("未找到ragflowApiUrl配置，请检查系统参数配置");
        }

        // 获取API Key
        QueryWrapper<ConfigParamsEntity> keyWrapper = new QueryWrapper<>();
        keyWrapper.eq("param_code", "apiKey");
        keyWrapper.last("limit 1");
        ConfigParamsEntity keyEntity = configParamsService.getOne(keyWrapper);
        if (keyEntity != null && StrUtil.isNotEmpty(keyEntity.getParamValue())) {
            apiKey = keyEntity.getParamValue();
            log.info("从配置表加载API密钥成功");
        } else {
            log.warn("未找到ragflowApiKey配置，请检查系统参数配置");
        }

        // 验证配置是否加载成功
        if (StrUtil.isEmpty(ragflowApiUrl)) {
            log.error("RAGFlow API URL未配置，将影响系统正常运行");
        }
    }


    /**
     * 创建HTTP头信息
     *
     * @return HTTP头信息
     */
    private HttpHeaders createHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        if (!StringUtils.isEmpty(apiKey)) {
            headers.set("Authorization", "Bearer " + apiKey);
        }
        return headers;
    }

    @Override
    public ResponseDTO<DatasetResponseDTO.DatasetData> createDataset(DatasetRequestDTO request) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.DATASETS_PATH;
            HttpEntity<DatasetRequestDTO> entity = new HttpEntity<>(request, createHeaders());
            ResponseEntity<DatasetResponseDTO> response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    DatasetResponseDTO.class
            );

            DatasetResponseDTO responseDTO = response.getBody();
            if (responseDTO != null && responseDTO.getCode() == RAGFlowApiConstants.SUCCESS_CODE) {
                return ResponseDTO.success(responseDTO.getData());
            } else {
                return ResponseDTO.error(
                        responseDTO != null ? responseDTO.getCode() : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseDTO != null ? responseDTO.getMessage() : "创建数据集失败"
                );
            }
        } catch (Exception e) {
            log.error("创建数据集异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "创建数据集异常: " + e.getMessage());
        }
    }

    @Override
    public ResponseDTO<DatasetResponseDTO.DatasetData> getDataset(String datasetId) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.DATASETS_PATH + "/" + datasetId;
            HttpEntity<Void> entity = new HttpEntity<>(createHeaders());
            ResponseEntity<DatasetResponseDTO> response = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    DatasetResponseDTO.class
            );

            DatasetResponseDTO responseDTO = response.getBody();
            if (responseDTO != null && responseDTO.getCode() == RAGFlowApiConstants.SUCCESS_CODE) {
                return ResponseDTO.success(responseDTO.getData());
            } else {
                return ResponseDTO.error(
                        responseDTO != null ? responseDTO.getCode() : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseDTO != null ? responseDTO.getMessage() : "获取数据集失败"
                );
            }
        } catch (Exception e) {
            log.error("获取数据集异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "获取数据集异常: " + e.getMessage());
        }
    }

    /**
     * 将RespBody转换为ResponseDTO
     *
     * @param respBody RespBody对象
     * @return ResponseDTO对象
     */
    private <T> ResponseDTO<T> convertToResponseDTO(RespBody<T> respBody) {
        if (respBody == null) {
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "响应为空");
        }

        if (respBody.isSuccess()) {
            return ResponseDTO.success(respBody.getData());
        } else {
            return ResponseDTO.error(respBody.getCode(), respBody.getMsg());
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public ResponseDTO<Map<String, Object>> listDatasets(Integer page, Integer pageSize, String orderBy, Boolean desc, String name, String id) {
        try {
            StringBuilder urlBuilder = new StringBuilder(ragflowApiUrl + RAGFlowApiConstants.DATASETS_PATH);
            urlBuilder.append("?page=").append(page != null ? page : 1);
            urlBuilder.append("&page_size=").append(pageSize != null ? pageSize : 30);

            if (!StringUtils.isEmpty(orderBy)) {
                urlBuilder.append("&orderby=").append(orderBy);
            }

            if (desc != null) {
                urlBuilder.append("&desc=").append(desc);
            }

            if (!StringUtils.isEmpty(name)) {
                urlBuilder.append("&name=").append(name);
            }

            if (!StringUtils.isEmpty(id)) {
                urlBuilder.append("&id=").append(id);
            }

            HttpEntity<Void> entity = new HttpEntity<>(createHeaders());
            ResponseEntity<Map> response = restTemplate.exchange(
                    urlBuilder.toString(),
                    HttpMethod.GET,
                    entity,
                    Map.class
            );

            Map responseMap = response.getBody();
            if (responseMap != null && responseMap.containsKey("code") && Integer.valueOf(0).equals(responseMap.get("code"))) {
                // 获取data对象
                Object dataObj = responseMap.get("data");
                Map<String, Object> resultMap = new HashMap<>();

                // 根据实际类型处理数据
                if (dataObj instanceof List) {
                    resultMap.put("data", dataObj);
                    resultMap.put("total", ((List) dataObj).size());
                } else if (dataObj instanceof Map) {
                    resultMap = (Map<String, Object>) dataObj;
                } else if (dataObj != null) {
                    resultMap.put("data", dataObj);
                }

                return ResponseDTO.success(resultMap);
            } else {
                return ResponseDTO.error(
                        responseMap != null && responseMap.containsKey("code") ? (Integer) responseMap.get("code") : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseMap != null && responseMap.containsKey("message") ? (String) responseMap.get("message") : "获取数据集列表失败"
                );
            }
        } catch (Exception e) {
            log.error("获取数据集列表异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "获取数据集列表异常: " + e.getMessage());
        }
    }

    @Override
    public ResponseDTO<Void> deleteDataset(String datasetId) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.DATASETS_PATH + "/" + datasetId;
            HttpEntity<Void> entity = new HttpEntity<>(createHeaders());
            ResponseEntity<ResponseDTO> response = restTemplate.exchange(
                    url,
                    HttpMethod.DELETE,
                    entity,
                    ResponseDTO.class
            );

            ResponseDTO responseDTO = response.getBody();
            if (responseDTO != null && responseDTO.getCode() == RAGFlowApiConstants.SUCCESS_CODE) {
                return ResponseDTO.success();
            } else {
                return ResponseDTO.error(
                        responseDTO != null ? responseDTO.getCode() : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseDTO != null ? responseDTO.getMessage() : "删除数据集失败"
                );
            }
        } catch (Exception e) {
            log.error("删除数据集异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "删除数据集异常: " + e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public ResponseDTO<Map<String, Object>> uploadDocument(String datasetId, MultipartFile file, String type, String chunkMethod, String parserConfig) {
        try {
            // 验证文件
            if (file == null || file.isEmpty()) {
                return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "文件不能为空");
            }

            // 验证文件类型
            String originalFilename = file.getOriginalFilename();
            if (!FileUtils.isSupportedDocType(originalFilename)) {
                return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "不支持的文件类型");
            }

            // 验证文件大小
            FileUtils.validateFileSize(file, maxUploadSizeMB);

            String url = ragflowApiUrl + RAGFlowApiConstants.DATASETS_PATH + "/" + datasetId + RAGFlowApiConstants.DOCUMENTS_PATH;

            // 设置HTTP头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            if (!StringUtils.isEmpty(apiKey)) {
                headers.set("Authorization", "Bearer " + apiKey);
            }

            // 创建multipart/form-data请求体
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();

            // 添加文件部分
            ByteArrayResource fileResource = new ByteArrayResource(file.getBytes()) {
                @Override
                public String getFilename() {
                    return file.getOriginalFilename();
                }
            };
            body.add("file", fileResource);

            // 添加其他参数
            if (!StringUtils.isEmpty(type)) {
                body.add("type", type);
            }

            if (!StringUtils.isEmpty(chunkMethod)) {
                body.add("chunk_method", chunkMethod);
            }

            if (!StringUtils.isEmpty(parserConfig)) {
                body.add("parser_config", parserConfig);
            }

            // 创建HTTP请求实体
            HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(body, headers);

            log.info("开始上传文件: {}, 大小: {} bytes, 类型: {}, 分块方法: {}",
                    originalFilename, file.getSize(), type, chunkMethod);

            // 发送请求
            ResponseEntity<Map> response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    Map.class
            );

            Map responseMap = response.getBody();
            if (responseMap != null && responseMap.containsKey("code") && Integer.valueOf(0).equals(responseMap.get("code"))) {
                log.info("文件上传成功: {}", originalFilename);
                // 获取data对象
                Object dataObj = responseMap.get("data");
                Map<String, Object> resultMap = new HashMap<>();

                // 根据实际类型处理数据
                if (dataObj instanceof List) {
                    log.info("uploadDocument: data is a List type");
                    resultMap.put("data", dataObj);
                    resultMap.put("total", ((List) dataObj).size());
                } else if (dataObj instanceof Map) {
                    log.info("uploadDocument: data is a Map type");
                    resultMap = (Map<String, Object>) dataObj;
                } else if (dataObj != null) {
                    log.info("uploadDocument: data is another type: {}", dataObj.getClass().getName());
                    resultMap.put("data", dataObj);
                }

                return ResponseDTO.success(resultMap);
            } else {
                log.error("文件上传失败: {}, 错误: {}", originalFilename,
                        responseMap != null ? responseMap.get("message") : "未知错误");
                return ResponseDTO.error(
                        responseMap != null && responseMap.containsKey("code") ? (Integer) responseMap.get("code") : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseMap != null && responseMap.containsKey("message") ? (String) responseMap.get("message") : "上传文档失败"
                );
            }
        } catch (FileUploadException e) {
            log.error("文件上传验证失败", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, e.getMessage());
        } catch (IOException e) {
            log.error("文件读取异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "文件读取异常: " + e.getMessage());
        } catch (Exception e) {
            log.error("上传文档异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "上传文档异常: " + e.getMessage());
        }
    }

    @Override
    public void downloadDocument(String datasetId, String documentId, HttpServletResponse response) {
        try {
            log.info("开始下载文档: datasetId={}, documentId={}", datasetId, documentId);

            String url = ragflowApiUrl + RAGFlowApiConstants.DATASETS_PATH + "/" + datasetId + RAGFlowApiConstants.DOCUMENTS_PATH + "/" + documentId;
            HttpHeaders headers = createHeaders();

            // 设置接受二进制流的响应格式
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_OCTET_STREAM));

            HttpEntity<Void> entity = new HttpEntity<>(headers);

            // 使用ResponseExtractor直接处理响应流，避免将整个文件加载到内存
            String fileName = restTemplate.execute(url, HttpMethod.GET, requestCallback -> {
                requestCallback.getHeaders().putAll(headers);
            }, responseExtractor -> {
                HttpStatus statusCode = responseExtractor.getStatusCode();

                if (statusCode.is2xxSuccessful()) {
                    // 从Content-Disposition头中获取真实的文件名
                    String contentDisposition = responseExtractor.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION);
                    String extractedFileName = documentId;

                    if (contentDisposition != null && contentDisposition.contains("filename=")) {
                        try {
                            extractedFileName = contentDisposition.split("filename=")[1].replaceAll("\"", "");
                        } catch (Exception e) {
                            log.warn("无法从Content-Disposition解析文件名，使用documentId作为文件名", e);
                        }
                    }

                    // 设置响应头
                    response.setContentType(responseExtractor.getHeaders().getContentType() != null ?
                            responseExtractor.getHeaders().getContentType().toString() : "application/octet-stream");
                    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + extractedFileName + "\"");

                    if (responseExtractor.getHeaders().getContentLength() > 0) {
                        response.setContentLengthLong(responseExtractor.getHeaders().getContentLength());
                    }

                    // 将文件内容写入响应
                    try (InputStream is = responseExtractor.getBody();
                         OutputStream os = response.getOutputStream()) {
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = is.read(buffer)) != -1) {
                            os.write(buffer, 0, bytesRead);
                        }
                        os.flush();
                    }

                    log.info("文档下载成功: {}", extractedFileName);
                    return extractedFileName;
                } else {
                    // 处理错误状态码
                    log.error("下载文档失败, 状态码: {}", statusCode);

                    // 读取错误响应
                    String errorBody = null;
                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(responseExtractor.getBody()))) {
                        errorBody = reader.lines().collect(Collectors.joining("\n"));
                    } catch (Exception e) {
                        log.error("读取错误响应失败", e);
                    }

                    response.setStatus(statusCode.value());
                    response.setContentType(MediaType.APPLICATION_JSON_VALUE);

                    try (PrintWriter writer = response.getWriter()) {
                        if (errorBody != null) {
                            writer.write(errorBody);
                        } else {
                            writer.write("{\"code\":" + statusCode.value() + ",\"message\":\"下载文档失败，HTTP状态码: " + statusCode.value() + "\"}");
                        }
                    }

                    return null;
                }
            });

            if (fileName == null) {
                log.warn("文档下载失败，响应处理中未返回文件名");
            }

        } catch (HttpClientErrorException e) {
            log.error("下载文档REST调用异常", e);
            handleDownloadError(response, HttpServletResponse.SC_BAD_GATEWAY, "下载文档REST调用异常: " + e.getMessage());
        } catch (Exception e) {
            log.error("下载文档异常", e);
            handleDownloadError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "下载文档异常: " + e.getMessage());
        }
    }

    /**
     * 处理下载错误，设置响应状态和错误消息
     */
    private void handleDownloadError(HttpServletResponse response, int statusCode, String errorMessage) {
        try {
            response.setStatus(statusCode);
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            PrintWriter writer = response.getWriter();
            writer.write("{\"code\":" + RAGFlowApiConstants.ERROR_CODE_COMMON + ",\"message\":\"" + errorMessage + "\"}");
        } catch (IOException ex) {
            log.error("写入错误响应异常", ex);
        }
    }

    @Override
    public ResponseDTO<DocumentResponseDTO.DocumentData> listDocuments(String datasetId, Integer page, Integer pageSize, String orderBy, Boolean desc, String keywords, String id, String name) {
        try {
            StringBuilder urlBuilder = new StringBuilder(ragflowApiUrl + RAGFlowApiConstants.DATASETS_PATH + "/" + datasetId + RAGFlowApiConstants.DOCUMENTS_PATH);
            urlBuilder.append("?page=").append(page != null ? page : 1);
            urlBuilder.append("&page_size=").append(pageSize != null ? pageSize : 30);

            if (!StringUtils.isEmpty(orderBy)) {
                urlBuilder.append("&orderby=").append(orderBy);
            }

            if (desc != null) {
                urlBuilder.append("&desc=").append(desc);
            }

            if (!StringUtils.isEmpty(keywords)) {
                urlBuilder.append("&keywords=").append(keywords);
            }

            if (!StringUtils.isEmpty(id)) {
                urlBuilder.append("&id=").append(id);
            }

            if (!StringUtils.isEmpty(name)) {
                urlBuilder.append("&name=").append(name);
            }

            HttpEntity<Void> entity = new HttpEntity<>(createHeaders());
            ResponseEntity<DocumentResponseDTO> response = restTemplate.exchange(
                    urlBuilder.toString(),
                    HttpMethod.GET,
                    entity,
                    DocumentResponseDTO.class
            );

            DocumentResponseDTO responseDTO = response.getBody();
            if (responseDTO != null && responseDTO.getCode() == RAGFlowApiConstants.SUCCESS_CODE) {
                return ResponseDTO.success(responseDTO.getData());
            } else {
                return ResponseDTO.error(
                        responseDTO != null ? responseDTO.getCode() : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseDTO != null ? responseDTO.getMessage() : "获取文档列表失败"
                );
            }
        } catch (Exception e) {
            log.error("获取文档列表异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "获取文档列表异常: " + e.getMessage());
        }
    }

    @Override
    public ResponseDTO<Void> deleteDocuments(String datasetId, List<String> ids) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.DATASETS_PATH + "/" + datasetId + RAGFlowApiConstants.DOCUMENTS_PATH;

            Map<String, List<String>> requestBody = new HashMap<>();
            // 如果ids为空，传递一个空数组，API会删除所有文档
            // 根据API文档：如果未指定ids，则删除指定数据集中的所有文档
            requestBody.put("ids", ids != null ? ids : new ArrayList<>());

            HttpEntity<Map<String, List<String>>> entity = new HttpEntity<>(requestBody, createHeaders());
            ResponseEntity<ResponseDTO> response = restTemplate.exchange(
                    url,
                    HttpMethod.DELETE,
                    entity,
                    ResponseDTO.class
            );

            ResponseDTO responseDTO = response.getBody();
            if (responseDTO != null && responseDTO.getCode() == RAGFlowApiConstants.SUCCESS_CODE) {
                return ResponseDTO.success();
            } else {
                return ResponseDTO.error(
                        responseDTO != null ? responseDTO.getCode() : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseDTO != null ? responseDTO.getMessage() : "删除文档失败"
                );
            }
        } catch (Exception e) {
            log.error("删除文档异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "删除文档异常: " + e.getMessage());
        }
    }

    @Override
    public ResponseDTO<Void> parseDocuments(String datasetId, List<String> documentIds) {
        try {
            // 验证参数
            if (StringUtils.isEmpty(datasetId)) {
                return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "dataset_id不能为空");
            }

            if (documentIds == null || documentIds.isEmpty()) {
                return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "`document_ids` is required");
            }

            // 构建请求URL和请求体
            String url = ragflowApiUrl + RAGFlowApiConstants.DATASETS_PATH + "/" + datasetId + RAGFlowApiConstants.CHUNKS_PATH;

            Map<String, List<String>> requestBody = new HashMap<>();
            requestBody.put("document_ids", documentIds);

            log.info("解析文档，数据集ID: {}, 文档IDs: {}", datasetId, documentIds);

            // 发送请求
            HttpEntity<Map<String, List<String>>> entity = new HttpEntity<>(requestBody, createHeaders());
            ResponseEntity<ResponseDTO> response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    ResponseDTO.class
            );

            // 处理响应
            ResponseDTO responseDTO = response.getBody();
            if (responseDTO != null && responseDTO.getCode() == RAGFlowApiConstants.SUCCESS_CODE) {
                log.info("解析文档成功，数据集ID: {}", datasetId);
                return ResponseDTO.success();
            } else {
                log.error("解析文档失败，数据集ID: {}, 错误码: {}, 错误信息: {}",
                          datasetId,
                          responseDTO != null ? responseDTO.getCode() : "未知",
                          responseDTO != null ? responseDTO.getMessage() : "未知");
                return ResponseDTO.error(
                        responseDTO != null ? responseDTO.getCode() : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseDTO != null ? responseDTO.getMessage() : "解析文档失败"
                );
            }
        } catch (Exception e) {
            log.error("解析文档异常，数据集ID: {}", datasetId, e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "解析文档异常: " + e.getMessage());
        }
    }

    @Override
    public ResponseDTO<Void> stopParsingDocuments(String datasetId, List<String> documentIds) {
        try {
            // 验证参数
            if (StringUtils.isEmpty(datasetId)) {
                log.error("停止解析文档失败：dataset_id不能为空");
                return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "dataset_id不能为空");
            }

            if (documentIds == null || documentIds.isEmpty()) {
                log.error("停止解析文档失败：document_ids不能为空");
                return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "`document_ids` is required");
            }

            // 构建请求URL和请求体
            String url = ragflowApiUrl + RAGFlowApiConstants.DATASETS_PATH + "/" + datasetId + RAGFlowApiConstants.CHUNKS_PATH;

            Map<String, List<String>> requestBody = new HashMap<>();
            requestBody.put("document_ids", documentIds);

            log.info("停止解析文档，数据集ID: {}, 文档IDs: {}, 请求URL: {}", datasetId, documentIds, url);

            // 发送请求
            HttpHeaders headers = createHeaders();
            HttpEntity<Map<String, List<String>>> entity = new HttpEntity<>(requestBody, headers);

            log.debug("停止解析文档请求体: {}", requestBody);

            ResponseEntity<ResponseDTO> response = restTemplate.exchange(
                    url,
                    HttpMethod.DELETE,
                    entity,
                    ResponseDTO.class
            );

            // 处理响应
            ResponseDTO responseDTO = response.getBody();
            if (responseDTO != null && responseDTO.getCode() == RAGFlowApiConstants.SUCCESS_CODE) {
                log.info("停止解析文档成功，数据集ID: {}", datasetId);
                return ResponseDTO.success();
            } else {
                String errorMessage = responseDTO != null ? responseDTO.getMessage() : "停止解析文档失败";
                int errorCode = responseDTO != null ? responseDTO.getCode() : RAGFlowApiConstants.ERROR_CODE_COMMON;

                log.error("停止解析文档失败，数据集ID: {}, 错误码: {}, 错误信息: {}",
                          datasetId, errorCode, errorMessage);

                return ResponseDTO.error(errorCode, errorMessage);
            }
        } catch (HttpClientErrorException e) {
            // 处理HTTP客户端错误，如400、404等
            log.error("停止解析文档HTTP错误，数据集ID: {}, 状态码: {}, 响应: {}",
                      datasetId, e.getStatusCode(), e.getResponseBodyAsString(), e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON,
                    "停止解析文档失败: " + e.getStatusCode() + " - " + e.getResponseBodyAsString());
        } catch (Exception e) {
            log.error("停止解析文档异常，数据集ID: {}", datasetId, e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "停止解析文档异常: " + e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public ResponseDTO<Map<String, Object>> createAssistant(AssistantRequestDTO request) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.ASSISTANTS_PATH;
            HttpEntity<AssistantRequestDTO> entity = new HttpEntity<>(request, createHeaders());
            ResponseEntity<Map> response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    Map.class
            );

            Map responseMap = response.getBody();
            if (responseMap != null && responseMap.containsKey("code") && Integer.valueOf(0).equals(responseMap.get("code"))) {
                return ResponseDTO.success(handleResponseData(responseMap));
            } else {
                return ResponseDTO.error(
                        responseMap != null && responseMap.containsKey("code") ? (Integer) responseMap.get("code") : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseMap != null && responseMap.containsKey("message") ? (String) responseMap.get("message") : "创建聊天助手失败"
                );
            }
        } catch (Exception e) {
            log.error("创建聊天助手异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "创建聊天助手异常: " + e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public ResponseDTO<Map<String, Object>> getAssistant(String assistantId) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.ASSISTANTS_PATH + "/" + assistantId;
            HttpEntity<Void> entity = new HttpEntity<>(createHeaders());
            ResponseEntity<Map> response = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    Map.class
            );

            Map responseMap = response.getBody();
            if (responseMap != null && responseMap.containsKey("code") && Integer.valueOf(0).equals(responseMap.get("code"))) {
                return ResponseDTO.success(handleResponseData(responseMap));
            } else {
                return ResponseDTO.error(
                        responseMap != null && responseMap.containsKey("code") ? (Integer) responseMap.get("code") : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseMap != null && responseMap.containsKey("message") ? (String) responseMap.get("message") : "获取聊天助手失败"
                );
            }
        } catch (Exception e) {
            log.error("获取聊天助手异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "获取聊天助手异常: " + e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public ResponseDTO<Map<String, Object>> updateAssistant(String assistantId, AssistantRequestDTO request) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.ASSISTANTS_PATH + "/" + assistantId;
            HttpEntity<AssistantRequestDTO> entity = new HttpEntity<>(request, createHeaders());
            ResponseEntity<Map> response = restTemplate.exchange(
                    url,
                    HttpMethod.PUT,
                    entity,
                    Map.class
            );

            Map responseMap = response.getBody();
            if (responseMap != null && responseMap.containsKey("code") && Integer.valueOf(0).equals(responseMap.get("code"))) {
                return ResponseDTO.success(handleResponseData(responseMap));
            } else {
                return ResponseDTO.error(
                        responseMap != null && responseMap.containsKey("code") ? (Integer) responseMap.get("code") : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseMap != null && responseMap.containsKey("message") ? (String) responseMap.get("message") : "更新聊天助手失败"
                );
            }
        } catch (Exception e) {
            log.error("更新聊天助手异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "更新聊天助手异常: " + e.getMessage());
        }
    }

    @Override
    public ResponseDTO<Void> deleteAssistant(String assistantId) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.ASSISTANTS_PATH + "/" + assistantId;
            HttpEntity<Void> entity = new HttpEntity<>(createHeaders());
            ResponseEntity<ResponseDTO> response = restTemplate.exchange(
                    url,
                    HttpMethod.DELETE,
                    entity,
                    ResponseDTO.class
            );

            ResponseDTO responseDTO = response.getBody();
            if (responseDTO != null && responseDTO.getCode() == RAGFlowApiConstants.SUCCESS_CODE) {
                return ResponseDTO.success();
            } else {
                return ResponseDTO.error(
                        responseDTO != null ? responseDTO.getCode() : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseDTO != null ? responseDTO.getMessage() : "删除聊天助手失败"
                );
            }
        } catch (Exception e) {
            log.error("删除聊天助手异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "删除聊天助手异常: " + e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public ResponseDTO<Map<String, Object>> listChats(Integer page, Integer pageSize, String orderBy, Boolean desc, String name, String id) {
        try {
            StringBuilder urlBuilder = new StringBuilder(ragflowApiUrl + RAGFlowApiConstants.CHATS_PATH);
            urlBuilder.append("?page=").append(page != null ? page : 1);
            urlBuilder.append("&page_size=").append(pageSize != null ? pageSize : 30);

            if (!StringUtils.isEmpty(orderBy)) {
                urlBuilder.append("&orderby=").append(orderBy);
            }

            if (desc != null) {
                urlBuilder.append("&desc=").append(desc);
            }

            if (!StringUtils.isEmpty(name)) {
                urlBuilder.append("&name=").append(name);
            }

            if (!StringUtils.isEmpty(id)) {
                urlBuilder.append("&id=").append(id);
            }

            HttpEntity<Void> entity = new HttpEntity<>(createHeaders());
            ResponseEntity<Map> response = restTemplate.exchange(
                    urlBuilder.toString(),
                    HttpMethod.GET,
                    entity,
                    Map.class
            );

            Map responseMap = response.getBody();
            if (responseMap != null && responseMap.containsKey("code") && Integer.valueOf(0).equals(responseMap.get("code"))) {
                Object dataObj = responseMap.get("data");
                Map<String, Object> resultMap = new HashMap<>();

                // 处理 data 是 ArrayList 的情况
                if (dataObj instanceof List) {
                    resultMap.put("data", dataObj);
                    resultMap.put("total", ((List) dataObj).size());
                }
                // 处理 data 是 Map 的情况
                else if (dataObj instanceof Map) {
                    resultMap = (Map<String, Object>) dataObj;
                }
                // 其他类型情况，直接包装
                else if (dataObj != null) {
                    resultMap.put("data", dataObj);
                }

                return ResponseDTO.success(resultMap);
            } else {
                return ResponseDTO.error(
                        responseMap != null && responseMap.containsKey("code") ? (Integer) responseMap.get("code") : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseMap != null && responseMap.containsKey("message") ? (String) responseMap.get("message") : "获取聊天助手列表失败"
                );
            }
        } catch (Exception e) {
            log.error("获取聊天助手列表异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "获取聊天助手列表异常: " + e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public ResponseDTO<Map<String, Object>> createSession(String chatId, SessionRequestDTO request) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.CHATS_PATH + "/" + chatId + RAGFlowApiConstants.SESSIONS_PATH;
            HttpEntity<SessionRequestDTO> entity = new HttpEntity<>(request, createHeaders());
            ResponseEntity<Map> response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    Map.class
            );

            Map responseMap = response.getBody();
            if (responseMap != null && responseMap.containsKey("code") && Integer.valueOf(0).equals(responseMap.get("code"))) {
                return ResponseDTO.success(handleResponseData(responseMap));
            } else {
                return ResponseDTO.error(
                        responseMap != null && responseMap.containsKey("code") ? (Integer) responseMap.get("code") : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseMap != null && responseMap.containsKey("message") ? (String) responseMap.get("message") : "创建聊天会话失败"
                );
            }
        } catch (Exception e) {
            log.error("创建聊天会话异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "创建聊天会话异常: " + e.getMessage());
        }
    }

    @Override
    public ResponseDTO<Void> updateSession(String chatId, String sessionId, SessionRequestDTO request) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.CHATS_PATH + "/" + chatId + RAGFlowApiConstants.SESSIONS_PATH + "/" + sessionId;
            HttpEntity<SessionRequestDTO> entity = new HttpEntity<>(request, createHeaders());
            ResponseEntity<ResponseDTO> response = restTemplate.exchange(
                    url,
                    HttpMethod.PUT,
                    entity,
                    ResponseDTO.class
            );

            ResponseDTO responseDTO = response.getBody();
            if (responseDTO != null && responseDTO.getCode() == RAGFlowApiConstants.SUCCESS_CODE) {
                return ResponseDTO.success();
            } else {
                return ResponseDTO.error(
                        responseDTO != null ? responseDTO.getCode() : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseDTO != null ? responseDTO.getMessage() : "更新聊天会话失败"
                );
            }
        } catch (Exception e) {
            log.error("更新聊天会话异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "更新聊天会话异常: " + e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public ResponseDTO<List<Map<String, Object>>> listSessions(String chatId, Integer page, Integer pageSize, String orderBy, Boolean desc, String name, String id, String userId) {
        try {
            StringBuilder urlBuilder = new StringBuilder(ragflowApiUrl + RAGFlowApiConstants.CHATS_PATH + "/" + chatId + RAGFlowApiConstants.SESSIONS_PATH);
            urlBuilder.append("?page=").append(page != null ? page : 1);
            urlBuilder.append("&page_size=").append(pageSize != null ? pageSize : 30);

            if (!StringUtils.isEmpty(orderBy)) {
                urlBuilder.append("&orderby=").append(orderBy);
            }

            if (desc != null) {
                urlBuilder.append("&desc=").append(desc);
            }

            if (!StringUtils.isEmpty(name)) {
                urlBuilder.append("&name=").append(name);
            }

            if (!StringUtils.isEmpty(id)) {
                urlBuilder.append("&id=").append(id);
            }

            if (!StringUtils.isEmpty(userId)) {
                // 确保使用API期望的参数名 user_id
                urlBuilder.append("&user_id=").append(userId);
            }

            HttpEntity<Void> entity = new HttpEntity<>(createHeaders());
            ResponseEntity<Map> response = restTemplate.exchange(
                    urlBuilder.toString(),
                    HttpMethod.GET,
                    entity,
                    Map.class
            );

            Map responseMap = response.getBody();
            if (responseMap != null && responseMap.containsKey("code") && Integer.valueOf(0).equals(responseMap.get("code"))) {
                // 获取data对象并转换为正确的返回类型
                Object dataObj = responseMap.get("data");

                // 确保返回List<Map<String, Object>>
                if (dataObj instanceof List) {
                    List<Map<String, Object>> resultList = (List<Map<String, Object>>) dataObj;

                    // 字段映射：确保每个会话对象中，如果有user_id字段，将其复制为userId字段
                    for (Map<String, Object> item : resultList) {
                        if (item.containsKey("user_id")) {
                            item.put("userId", item.get("user_id"));
                        }
                        // 反向兼容：如果只有userId字段，也复制为user_id
                        else if (item.containsKey("userId") && !item.containsKey("user_id")) {
                            item.put("user_id", item.get("userId"));
                        }
                    }

                    return ResponseDTO.success(resultList);
                } else if (dataObj instanceof Map) {
                    // 如果是Map类型，需要处理为List
                    Map<String, Object> dataMap = (Map<String, Object>) dataObj;
                    if (dataMap.containsKey("data") && dataMap.get("data") instanceof List) {
                        List<Map<String, Object>> resultList = (List<Map<String, Object>>) dataMap.get("data");

                        // 字段映射：确保每个会话对象中，如果有user_id字段，将其复制为userId字段
                        for (Map<String, Object> item : resultList) {
                            if (item.containsKey("user_id")) {
                                item.put("userId", item.get("user_id"));
                            }
                            // 反向兼容：如果只有userId字段，也复制为user_id
                            else if (item.containsKey("userId") && !item.containsKey("user_id")) {
                                item.put("user_id", item.get("userId"));
                            }
                        }

                        return ResponseDTO.success(resultList);
                    } else {
                        // 将单个Map包装为List返回
                        List<Map<String, Object>> resultList = new ArrayList<>();

                        // 字段映射：确保如果有user_id字段，将其复制为userId字段
                        if (dataMap.containsKey("user_id")) {
                            dataMap.put("userId", dataMap.get("user_id"));
                        }
                        // 反向兼容：如果只有userId字段，也复制为user_id
                        else if (dataMap.containsKey("userId") && !dataMap.containsKey("user_id")) {
                            dataMap.put("user_id", dataMap.get("userId"));
                        }

                        resultList.add(dataMap);
                        return ResponseDTO.success(resultList);
                    }
                } else if (dataObj != null) {
                    // 其他类型处理(不太可能出现)
                    log.warn("listSessions: 意外的数据类型: {}", dataObj.getClass().getName());
                    return ResponseDTO.success(new ArrayList<>());
                } else {
                    // 数据为空
                    return ResponseDTO.success(new ArrayList<>());
                }
            } else {
                return ResponseDTO.error(
                        responseMap != null && responseMap.containsKey("code") ? (Integer) responseMap.get("code") : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseMap != null && responseMap.containsKey("message") ? (String) responseMap.get("message") : "获取聊天会话列表失败"
                );
            }
        } catch (Exception e) {
            log.error("获取聊天会话列表异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "获取聊天会话列表异常: " + e.getMessage());
        }
    }

    @Override
    public ResponseDTO<Void> deleteSessions(String chatId, List<String> ids) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.CHATS_PATH + "/" + chatId + RAGFlowApiConstants.SESSIONS_PATH;

            Map<String, List<String>> requestBody = new HashMap<>();
            if (ids != null && !ids.isEmpty()) {
                requestBody.put("ids", ids);
            }

            HttpEntity<Map<String, List<String>>> entity = new HttpEntity<>(requestBody, createHeaders());
            ResponseEntity<ResponseDTO> response = restTemplate.exchange(
                    url,
                    HttpMethod.DELETE,
                    entity,
                    ResponseDTO.class
            );

            ResponseDTO responseDTO = response.getBody();
            if (responseDTO != null && responseDTO.getCode() == RAGFlowApiConstants.SUCCESS_CODE) {
                return ResponseDTO.success();
            } else {
                return ResponseDTO.error(
                        responseDTO != null ? responseDTO.getCode() : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseDTO != null ? responseDTO.getMessage() : "删除聊天会话失败"
                );
            }
        } catch (Exception e) {
            log.error("删除聊天会话异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "删除聊天会话异常: " + e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public ResponseDTO<Map<String, Object>> chatCompletion(String chatId, CompletionRequestDTO request) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.CHATS_PATH + "/" + chatId + RAGFlowApiConstants.COMPLETIONS_PATH;

            // 创建请求体，处理other_params
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("question", request.getQuestion());
            if (request.getStream() != null) {
                requestBody.put("stream", request.getStream());
            }
            if (request.getSessionId() != null) {
                requestBody.put("session_id", request.getSessionId());
            }
            if (request.getUserId() != null) {
                requestBody.put("user_id", request.getUserId());
            }

            // 添加Begin组件中指定的其他参数
            if (request.getOtherParams() != null && !request.getOtherParams().isEmpty()) {
                requestBody.putAll(request.getOtherParams());
            }

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, createHeaders());
            ResponseEntity<Map> response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    Map.class
            );

            Map responseMap = response.getBody();
            if (responseMap != null && responseMap.containsKey("code") && Integer.valueOf(0).equals(responseMap.get("code"))) {
                return ResponseDTO.success(handleResponseData(responseMap));
            } else {
                return ResponseDTO.error(
                        responseMap != null && responseMap.containsKey("code") ? (Integer) responseMap.get("code") : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseMap != null && responseMap.containsKey("message") ? (String) responseMap.get("message") : "聊天助手对话失败"
                );
            }
        } catch (Exception e) {
            log.error("聊天助手对话异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "聊天助手对话异常: " + e.getMessage());
        }
    }

    @Override
    public ResponseDTO<Map<String, Object>> agentCompletion(String agentId, CompletionRequestDTO request) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.AGENTS_PATH + "/" + agentId + RAGFlowApiConstants.COMPLETIONS_PATH;

            // 创建请求体，处理other_params
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("question", request.getQuestion());
            if (request.getStream() != null) {
                requestBody.put("stream", request.getStream());
            }
            if (request.getSessionId() != null) {
                requestBody.put("session_id", request.getSessionId());
            }
            if (request.getUserId() != null) {
                requestBody.put("user_id", request.getUserId());
            }

            // 添加Begin组件中指定的其他参数
            if (request.getOtherParams() != null && !request.getOtherParams().isEmpty()) {
                requestBody.putAll(request.getOtherParams());
            }

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, createHeaders());
            ResponseEntity<Map> response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    Map.class
            );

            Map responseMap = response.getBody();
            if (responseMap != null && responseMap.containsKey("code") && Integer.valueOf(0).equals(responseMap.get("code"))) {
                return ResponseDTO.success(handleResponseData(responseMap));
            } else {
                return ResponseDTO.error(
                        responseMap != null && responseMap.containsKey("code") ? (Integer) responseMap.get("code") : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseMap != null && responseMap.containsKey("message") ? (String) responseMap.get("message") : "代理对话失败"
                );
            }
        } catch (Exception e) {
            log.error("代理对话异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "代理对话异常: " + e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public ResponseDTO<Map<String, Object>> createAgent(AgentRequestDTO request) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.AGENTS_PATH;
            HttpEntity<AgentRequestDTO> entity = new HttpEntity<>(request, createHeaders());
            ResponseEntity<Map> response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    Map.class
            );

            Map responseMap = response.getBody();
            if (responseMap != null && responseMap.containsKey("code") && Integer.valueOf(0).equals(responseMap.get("code"))) {
                return ResponseDTO.success(handleResponseData(responseMap));
            } else {
                return ResponseDTO.error(
                        responseMap != null && responseMap.containsKey("code") ? (Integer) responseMap.get("code") : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseMap != null && responseMap.containsKey("message") ? (String) responseMap.get("message") : "创建代理失败"
                );
            }
        } catch (Exception e) {
            log.error("创建代理异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "创建代理异常: " + e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public ResponseDTO<Map<String, Object>> getAgent(String agentId) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.AGENTS_PATH + "/" + agentId;
            HttpEntity<Void> entity = new HttpEntity<>(createHeaders());
            ResponseEntity<Map> response = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    Map.class
            );

            Map responseMap = response.getBody();
            if (responseMap != null && responseMap.containsKey("code") && Integer.valueOf(0).equals(responseMap.get("code"))) {
                return ResponseDTO.success(handleResponseData(responseMap));
            } else {
                return ResponseDTO.error(
                        responseMap != null && responseMap.containsKey("code") ? (Integer) responseMap.get("code") : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseMap != null && responseMap.containsKey("message") ? (String) responseMap.get("message") : "获取代理失败"
                );
            }
        } catch (Exception e) {
            log.error("获取代理异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "获取代理异常: " + e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public ResponseDTO<Map<String, Object>> updateAgent(String agentId, AgentRequestDTO request) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.AGENTS_PATH + "/" + agentId;
            HttpEntity<AgentRequestDTO> entity = new HttpEntity<>(request, createHeaders());
            ResponseEntity<Map> response = restTemplate.exchange(
                    url,
                    HttpMethod.PUT,
                    entity,
                    Map.class
            );

            Map responseMap = response.getBody();
            if (responseMap != null && responseMap.containsKey("code") && Integer.valueOf(0).equals(responseMap.get("code"))) {
                return ResponseDTO.success(handleResponseData(responseMap));
            } else {
                return ResponseDTO.error(
                        responseMap != null && responseMap.containsKey("code") ? (Integer) responseMap.get("code") : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseMap != null && responseMap.containsKey("message") ? (String) responseMap.get("message") : "更新代理失败"
                );
            }
        } catch (Exception e) {
            log.error("更新代理异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "更新代理异常: " + e.getMessage());
        }
    }

    @Override
    public ResponseDTO<Void> deleteAgent(String agentId) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.AGENTS_PATH + "/" + agentId;
            HttpEntity<Void> entity = new HttpEntity<>(createHeaders());
            ResponseEntity<ResponseDTO> response = restTemplate.exchange(
                    url,
                    HttpMethod.DELETE,
                    entity,
                    ResponseDTO.class
            );

            ResponseDTO responseDTO = response.getBody();
            if (responseDTO != null && responseDTO.getCode() == RAGFlowApiConstants.SUCCESS_CODE) {
                return ResponseDTO.success();
            } else {
                return ResponseDTO.error(
                        responseDTO != null ? responseDTO.getCode() : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseDTO != null ? responseDTO.getMessage() : "删除代理失败"
                );
            }
        } catch (Exception e) {
            log.error("删除代理异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "删除代理异常: " + e.getMessage());
        }
    }

    @Override
    public ResponseDTO<AgentResponseDTO.AgentData> listAgents(Integer page, Integer pageSize, String orderBy, Boolean desc, String keywords) {
        try {
            StringBuilder urlBuilder = new StringBuilder(ragflowApiUrl + RAGFlowApiConstants.AGENTS_PATH);
            urlBuilder.append("?page=").append(page != null ? page : 1);
            urlBuilder.append("&page_size=").append(pageSize != null ? pageSize : 30);

            if (!StringUtils.isEmpty(orderBy)) {
                urlBuilder.append("&orderby=").append(orderBy);
            }

            if (desc != null) {
                urlBuilder.append("&desc=").append(desc);
            }

            if (!StringUtils.isEmpty(keywords)) {
                urlBuilder.append("&keywords=").append(keywords);
            }

            HttpEntity<Void> entity = new HttpEntity<>(createHeaders());
            ResponseEntity<AgentResponseDTO> response = restTemplate.exchange(
                    urlBuilder.toString(),
                    HttpMethod.GET,
                    entity,
                    AgentResponseDTO.class
            );

            AgentResponseDTO responseDTO = response.getBody();
            if (responseDTO != null && responseDTO.getCode() == RAGFlowApiConstants.SUCCESS_CODE) {
                return ResponseDTO.success(responseDTO.getData());
            } else {
                return ResponseDTO.error(
                        responseDTO != null ? responseDTO.getCode() : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseDTO != null ? responseDTO.getMessage() : "获取代理列表失败"
                );
            }
        } catch (Exception e) {
            log.error("获取代理列表异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "获取代理列表异常: " + e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public ResponseDTO<Map<String, Object>> createAgentSession(String agentId, Map<String, Object> request, String userId, MultipartFile file) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.AGENTS_PATH + "/" + agentId + RAGFlowApiConstants.SESSIONS_PATH;

            // 如果提供了userId，将其添加到URL作为查询参数
            if (!StringUtils.isEmpty(userId)) {
                url += "?user_id=" + userId;
            }

            ResponseEntity<Map> response;

            // 根据是否提供文件决定使用哪种请求方式
            if (file != null && !file.isEmpty()) {
                // 使用multipart/form-data方式发送请求
                MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();

                // 添加文件
                try {
                    ByteArrayResource resource = new ByteArrayResource(file.getBytes()) {
                        @Override
                        public String getFilename() {
                            return file.getOriginalFilename();
                        }
                    };
                    multipartRequest.add(file.getName(), resource);
                } catch (IOException e) {
                    log.error("处理文件异常", e);
                    throw new FileUploadException("处理文件异常: " + e.getMessage());
                }

                // 添加其他参数
                for (Map.Entry<String, Object> entry : request.entrySet()) {
                    multipartRequest.add(entry.getKey(), entry.getValue());
                }

                // 创建请求头
                HttpHeaders headers = createHeaders();
                headers.setContentType(MediaType.MULTIPART_FORM_DATA);

                HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(multipartRequest, headers);
                response = restTemplate.exchange(
                        url,
                        HttpMethod.POST,
                        entity,
                        Map.class
                );
            } else {
                // 使用application/json方式发送请求
                HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, createHeaders());
                response = restTemplate.exchange(
                        url,
                        HttpMethod.POST,
                        entity,
                        Map.class
                );
            }

            Map responseMap = response.getBody();
            if (responseMap != null && responseMap.containsKey("code") && Integer.valueOf(0).equals(responseMap.get("code"))) {
                return ResponseDTO.success(handleResponseData(responseMap));
            } else {
                return ResponseDTO.error(
                        responseMap != null && responseMap.containsKey("code") ? (Integer) responseMap.get("code") : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseMap != null && responseMap.containsKey("message") ? (String) responseMap.get("message") : "创建代理会话失败"
                );
            }
        } catch (Exception e) {
            log.error("创建代理会话异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "创建代理会话异常: " + e.getMessage());
        }
    }


    @Override
    public ResponseDTO<ThreadResponseDTO.ThreadData> listAgentThreads(String agentId, Integer page, Integer pageSize, String orderBy, Boolean desc, String id, String userId) {
        try {
            StringBuilder urlBuilder = new StringBuilder(ragflowApiUrl + RAGFlowApiConstants.AGENTS_PATH + "/" + agentId + RAGFlowApiConstants.THREADS_PATH);
            urlBuilder.append("?page=").append(page != null ? page : 1);
            urlBuilder.append("&page_size=").append(pageSize != null ? pageSize : 30);

            if (!StringUtils.isEmpty(orderBy)) {
                urlBuilder.append("&orderby=").append(orderBy);
            }

            if (desc != null) {
                urlBuilder.append("&desc=").append(desc);
            }

            if (!StringUtils.isEmpty(id)) {
                urlBuilder.append("&id=").append(id);
            }

            if (!StringUtils.isEmpty(userId)) {
                urlBuilder.append("&user_id=").append(userId);
            }

            HttpEntity<Void> entity = new HttpEntity<>(createHeaders());
            ResponseEntity<ThreadResponseDTO> response = restTemplate.exchange(
                    urlBuilder.toString(),
                    HttpMethod.GET,
                    entity,
                    ThreadResponseDTO.class
            );

            ThreadResponseDTO responseDTO = response.getBody();
            if (responseDTO != null && responseDTO.getCode() == RAGFlowApiConstants.SUCCESS_CODE) {
                return ResponseDTO.success(responseDTO.getData());
            } else {
                return ResponseDTO.error(
                        responseDTO != null ? responseDTO.getCode() : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseDTO != null ? responseDTO.getMessage() : "获取代理会话列表失败"
                );
            }
        } catch (Exception e) {
            log.error("获取代理会话列表异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "获取代理会话列表异常: " + e.getMessage());
        }
    }

    @Override
    public ResponseDTO<DatasetResponseDTO.DatasetData> updateDataset(String datasetId, DatasetRequestDTO request) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.DATASETS_PATH + "/" + datasetId;
            HttpEntity<DatasetRequestDTO> entity = new HttpEntity<>(request, createHeaders());
            ResponseEntity<DatasetResponseDTO> response = restTemplate.exchange(
                    url,
                    HttpMethod.PUT,
                    entity,
                    DatasetResponseDTO.class
            );

            DatasetResponseDTO responseDTO = response.getBody();
            if (responseDTO != null && responseDTO.getCode() == RAGFlowApiConstants.SUCCESS_CODE) {
                return ResponseDTO.success(responseDTO.getData());
            } else {
                return ResponseDTO.error(
                        responseDTO != null ? responseDTO.getCode() : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseDTO != null ? responseDTO.getMessage() : "更新数据集失败"
                );
            }
        } catch (Exception e) {
            log.error("更新数据集异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "更新数据集异常: " + e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public ResponseDTO<Map<String, Object>> updateDocument(String datasetId, String documentId, DocumentRequestDTO request) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.DATASETS_PATH + "/" + datasetId + RAGFlowApiConstants.DOCUMENTS_PATH + "/" + documentId;
            HttpEntity<DocumentRequestDTO> entity = new HttpEntity<>(request, createHeaders());
            ResponseEntity<Map> response = restTemplate.exchange(
                    url,
                    HttpMethod.PUT,
                    entity,
                    Map.class
            );

            Map responseMap = response.getBody();
            if (responseMap != null && responseMap.containsKey("code") && Integer.valueOf(0).equals(responseMap.get("code"))) {
                // 成功响应，API预期返回空data或者空结果
                Map<String, Object> emptyData = new HashMap<>();
                return ResponseDTO.success(emptyData);
            } else {
                return ResponseDTO.error(
                        responseMap != null && responseMap.containsKey("code") ? (Integer) responseMap.get("code") : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseMap != null && responseMap.containsKey("message") ? (String) responseMap.get("message") : "更新文档失败"
                );
            }
        } catch (Exception e) {
            log.error("更新文档异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "更新文档异常: " + e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public ResponseDTO<Map<String, Object>> addChunk(String datasetId, ChunkRequestDTO request) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.DATASETS_PATH + "/" + datasetId + RAGFlowApiConstants.CHUNKS_PATH;
            HttpEntity<ChunkRequestDTO> entity = new HttpEntity<>(request, createHeaders());
            ResponseEntity<Map> response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    Map.class
            );

            Map responseMap = response.getBody();
            if (responseMap != null && responseMap.containsKey("code") && Integer.valueOf(0).equals(responseMap.get("code"))) {
                return ResponseDTO.success(handleResponseData(responseMap));
            } else {
                return ResponseDTO.error(
                        responseMap != null && responseMap.containsKey("code") ? (Integer) responseMap.get("code") : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseMap != null && responseMap.containsKey("message") ? (String) responseMap.get("message") : "添加块失败"
                );
            }
        } catch (Exception e) {
            log.error("添加块异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "添加块异常: " + e.getMessage());
        }
    }

    @Override
    public ResponseDTO<ChunkResponseDTO.ChunkData> listChunks(String datasetId, Integer page, Integer pageSize, String documentId) {
        try {
            StringBuilder urlBuilder = new StringBuilder(ragflowApiUrl + RAGFlowApiConstants.DATASETS_PATH + "/" + datasetId + RAGFlowApiConstants.CHUNKS_PATH);
            urlBuilder.append("?page=").append(page != null ? page : 1);
            urlBuilder.append("&page_size=").append(pageSize != null ? pageSize : 30);

            if (!StringUtils.isEmpty(documentId)) {
                urlBuilder.append("&document_id=").append(documentId);
            }

            HttpEntity<Void> entity = new HttpEntity<>(createHeaders());
            ResponseEntity<ChunkResponseDTO> response = restTemplate.exchange(
                    urlBuilder.toString(),
                    HttpMethod.GET,
                    entity,
                    ChunkResponseDTO.class
            );

            ChunkResponseDTO responseDTO = response.getBody();
            if (responseDTO != null && responseDTO.getCode() == RAGFlowApiConstants.SUCCESS_CODE) {
                return ResponseDTO.success(responseDTO.getData());
            } else {
                return ResponseDTO.error(
                        responseDTO != null ? responseDTO.getCode() : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseDTO != null ? responseDTO.getMessage() : "获取块列表失败"
                );
            }
        } catch (Exception e) {
            log.error("获取块列表异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "获取块列表异常: " + e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public ResponseDTO<Map<String, Object>> updateChunk(String datasetId, String chunkId, ChunkRequestDTO request) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.DATASETS_PATH + "/" + datasetId + RAGFlowApiConstants.CHUNKS_PATH + "/" + chunkId;
            HttpEntity<ChunkRequestDTO> entity = new HttpEntity<>(request, createHeaders());
            ResponseEntity<Map> response = restTemplate.exchange(
                    url,
                    HttpMethod.PUT,
                    entity,
                    Map.class
            );

            Map responseMap = response.getBody();
            if (responseMap != null && responseMap.containsKey("code") && Integer.valueOf(0).equals(responseMap.get("code"))) {
                return ResponseDTO.success(handleResponseData(responseMap));
            } else {
                return ResponseDTO.error(
                        responseMap != null && responseMap.containsKey("code") ? (Integer) responseMap.get("code") : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseMap != null && responseMap.containsKey("message") ? (String) responseMap.get("message") : "更新块失败"
                );
            }
        } catch (Exception e) {
            log.error("更新块异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "更新块异常: " + e.getMessage());
        }
    }

    @Override
    public ResponseDTO<Void> deleteChunks(String datasetId, List<String> ids) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.DATASETS_PATH + "/" + datasetId + RAGFlowApiConstants.CHUNKS_PATH;

            Map<String, List<String>> requestBody = new HashMap<>();
            requestBody.put("ids", ids);

            HttpEntity<Map<String, List<String>>> entity = new HttpEntity<>(requestBody, createHeaders());
            ResponseEntity<ResponseDTO> response = restTemplate.exchange(
                    url,
                    HttpMethod.DELETE,
                    entity,
                    ResponseDTO.class
            );

            ResponseDTO responseDTO = response.getBody();
            if (responseDTO != null && responseDTO.getCode() == RAGFlowApiConstants.SUCCESS_CODE) {
                return ResponseDTO.success();
            } else {
                return ResponseDTO.error(
                        responseDTO != null ? responseDTO.getCode() : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseDTO != null ? responseDTO.getMessage() : "删除块失败"
                );
            }
        } catch (Exception e) {
            log.error("删除块异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "删除块异常: " + e.getMessage());
        }
    }

    @Override
    public ResponseDTO<ChunkResponseDTO.ChunkData> searchChunks(String datasetId, ChunkRequestDTO request) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.DATASETS_PATH + "/" + datasetId + RAGFlowApiConstants.SEARCH_PATH;
            HttpEntity<ChunkRequestDTO> entity = new HttpEntity<>(request, createHeaders());
            ResponseEntity<ChunkResponseDTO> response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    ChunkResponseDTO.class
            );

            ChunkResponseDTO responseDTO = response.getBody();
            if (responseDTO != null && responseDTO.getCode() == RAGFlowApiConstants.SUCCESS_CODE) {
                return ResponseDTO.success(responseDTO.getData());
            } else {
                return ResponseDTO.error(
                        responseDTO != null ? responseDTO.getCode() : RAGFlowApiConstants.ERROR_CODE_COMMON,
                        responseDTO != null ? responseDTO.getMessage() : "检索块失败"
                );
            }
        } catch (Exception e) {
            log.error("检索块异常", e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "检索块异常: " + e.getMessage());
        }
    }

    @Override
    public void streamChatCompletion(String chatId, CompletionRequestDTO request, HttpServletResponse response) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.CHATS_PATH + "/" + chatId + RAGFlowApiConstants.COMPLETIONS_PATH;

            // 强制设置stream为true
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("question", request.getQuestion());
            requestBody.put("stream", true);
            if (request.getSessionId() != null) {
                requestBody.put("session_id", request.getSessionId());
            }
            if (request.getUserId() != null) {
                requestBody.put("user_id", request.getUserId());
            }

            // 添加Begin组件中指定的其他参数
            if (request.getOtherParams() != null && !request.getOtherParams().isEmpty()) {
                requestBody.putAll(request.getOtherParams());
            }

            // 创建HTTP请求头
            HttpHeaders headers = createHeaders();
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

            // 使用RestTemplate进行请求，但是需要处理流式响应
            // 这里我们使用底层的ClientHttpRequest来手动处理流式响应
            ClientHttpRequestFactory factory = restTemplate.getRequestFactory();
            ClientHttpRequest clientHttpRequest = factory.createRequest(
                    new URI(url), HttpMethod.POST);

            // 设置请求头
            clientHttpRequest.getHeaders().putAll(headers);

            // 写入请求体
            ObjectMapper objectMapper = new ObjectMapper();
            clientHttpRequest.getBody().write(objectMapper.writeValueAsBytes(requestBody));

            try (ClientHttpResponse clientResponse = clientHttpRequest.execute();
                 PrintWriter writer = response.getWriter()) {

                // 检查响应状态
                if (clientResponse.getStatusCode() != HttpStatus.OK) {
                    // 如果不是成功的状态码，发送错误信息
                    String errorMessage = String.format("data: {\"error\":\"Failed to fetch from RAGFlow API. Status: %s\"}\n\n",
                            clientResponse.getStatusCode());
                    writer.write(errorMessage);
                    writer.flush();
                    return;
                }

                // 读取响应流并实时转发到客户端
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(clientResponse.getBody()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        writer.write(line + "\n");
                        if (line.isEmpty()) {
                            writer.flush();
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("流式聊天异常", e);
            try {
                // 发送错误信息到客户端
                PrintWriter writer = response.getWriter();
                writer.write("data: {\"error\":\"" + e.getMessage().replace("\"", "\\\"") + "\"}\n\n");
                writer.flush();
            } catch (IOException ioe) {
                log.error("发送错误消息异常", ioe);
            }
        }
    }

    @Override
    public void streamAgentCompletion(String agentId, CompletionRequestDTO request, HttpServletResponse response) {
        try {
            String url = ragflowApiUrl + RAGFlowApiConstants.AGENTS_PATH + "/" + agentId + RAGFlowApiConstants.COMPLETIONS_PATH;

            // 强制设置stream为true
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("question", request.getQuestion());
            requestBody.put("stream", true);
            if (request.getSessionId() != null) {
                requestBody.put("session_id", request.getSessionId());
            }
            if (request.getUserId() != null) {
                requestBody.put("user_id", request.getUserId());
            }

            // 添加Begin组件中指定的其他参数
            if (request.getOtherParams() != null && !request.getOtherParams().isEmpty()) {
                requestBody.putAll(request.getOtherParams());
            }

            // 创建HTTP请求头
            HttpHeaders headers = createHeaders();
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

            // 使用RestTemplate进行请求，但是需要处理流式响应
            // 这里我们使用底层的ClientHttpRequest来手动处理流式响应
            ClientHttpRequestFactory factory = restTemplate.getRequestFactory();
            ClientHttpRequest clientHttpRequest = factory.createRequest(
                    new URI(url), HttpMethod.POST);

            // 设置请求头
            clientHttpRequest.getHeaders().putAll(headers);

            // 写入请求体
            ObjectMapper objectMapper = new ObjectMapper();
            clientHttpRequest.getBody().write(objectMapper.writeValueAsBytes(requestBody));

            try (ClientHttpResponse clientResponse = clientHttpRequest.execute();
                 PrintWriter writer = response.getWriter()) {

                // 检查响应状态
                if (clientResponse.getStatusCode() != HttpStatus.OK) {
                    // 如果不是成功的状态码，发送错误信息
                    String errorMessage = String.format("data: {\"error\":\"Failed to fetch from RAGFlow API. Status: %s\"}\n\n",
                            clientResponse.getStatusCode());
                    writer.write(errorMessage);
                    writer.flush();
                    return;
                }

                // 读取响应流并实时转发到客户端
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(clientResponse.getBody()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        writer.write(line + "\n");
                        if (line.isEmpty()) {
                            writer.flush();
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("流式对话异常", e);
            try {
                // 发送错误信息到客户端
                PrintWriter writer = response.getWriter();
                writer.write("data: {\"error\":\"" + e.getMessage().replace("\"", "\\\"") + "\"}\n\n");
                writer.flush();
            } catch (IOException ioe) {
                log.error("发送错误消息异常", ioe);
            }
        }
    }

    /**
     * 处理API响应数据，确保适当处理不同类型的返回值
     * @param responseMap API响应Map
     * @return 处理后的数据Map
     */
    @SuppressWarnings("unchecked")
    private Map<String, Object> handleResponseData(Map responseMap) {
        if (responseMap == null || !responseMap.containsKey("data")) {
            return new HashMap<>();
        }

        Object dataObj = responseMap.get("data");
        Map<String, Object> resultMap = new HashMap<>();

        // 根据data对象的实际类型进行处理
        if (dataObj instanceof List) {
            // 如果是列表，将其放入data键中，并添加total键表示总数
            resultMap.put("data", dataObj);
            resultMap.put("total", ((List) dataObj).size());
        } else if (dataObj instanceof Map) {
            // 如果已经是Map类型，直接转换使用
            resultMap = (Map<String, Object>) dataObj;
        } else if (dataObj != null) {
            // 处理其他类型的数据
            resultMap.put("data", dataObj);
        }

        return resultMap;
    }

    @Override
    public ResponseDTO<TenantJoinResponseDTO> joinTenant(TenantJoinRequestDTO request) {
        log.info("开始处理加入租户请求，请求参数: {}", request);
        try {
            // 获取defaultTenant  默认团队
            log.info("开始查询默认团队配置");
            QueryWrapper<ConfigParamsEntity> keyWrapper = new QueryWrapper<>();
            keyWrapper.eq("param_code", "defaultTenant");
            keyWrapper.last("limit 1");
            ConfigParamsEntity keyEntity = configParamsService.getOne(keyWrapper);
            if(Objects.isNull(keyEntity)){
                log.error("未找到默认团队配置【defaultTenant】");
                throw new RuntimeException("未配置默认团队【defaultTenant】");
            }
            log.info("成功获取默认团队配置，团队ID: {}", keyEntity.getParamValue());

            // 构建请求URL
            String url = ragflowApiUrl + RAGFlowApiConstants.TENANT_PATH + "/" + keyEntity.getParamValue() + "/join";
            log.info("构建请求URL: {}", url);

            // 创建HTTP请求实体
            HttpEntity<TenantJoinRequestDTO> entity = new HttpEntity<>(request, createHeaders());
            log.info("创建HTTP请求实体完成");

            // 发送请求
            log.info("开始发送加入租户请求");
            ResponseEntity<Map> response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    Map.class
            );
            log.info("收到加入租户响应，状态码: {}", response.getStatusCode());

            Map responseMap = response.getBody();
            log.info("响应内容: {}", responseMap);

            if (responseMap != null && responseMap.containsKey("code") && Integer.valueOf(0).equals(responseMap.get("code"))) {
                log.info("响应成功，开始处理返回数据");
                // 获取data对象并转换为TenantJoinResponseDTO
                Object dataObj = responseMap.get("data");
                if (dataObj instanceof Map) {
                    Map<String, Object> dataMap = (Map<String, Object>) dataObj;
                    TenantJoinResponseDTO responseData = new TenantJoinResponseDTO();
                    responseData.setAvatar((String) dataMap.get("avatar"));
                    responseData.setEmail((String) dataMap.get("email"));
                    responseData.setId((String) dataMap.get("id"));
                    responseData.setNickname((String) dataMap.get("nickname"));
                    responseData.setRole((String) dataMap.get("role"));
                    responseData.setTenantId(keyEntity.getParamValue());

                    log.info("成功处理返回数据，用户信息: {}", responseData);
                    return ResponseDTO.success(responseData);
                } else {
                    log.error("响应数据格式错误，data不是Map类型: {}", dataObj);
                }
            }

            // 处理错误响应
            log.error("加入租户失败，错误码: {}, 错误信息: {}", 
                responseMap != null && responseMap.containsKey("code") ? responseMap.get("code") : RAGFlowApiConstants.ERROR_CODE_COMMON,
                responseMap != null && responseMap.containsKey("message") ? responseMap.get("message") : "加入租户失败"
            );
            return ResponseDTO.error(
                    responseMap != null && responseMap.containsKey("code") ? (Integer) responseMap.get("code") : RAGFlowApiConstants.ERROR_CODE_COMMON,
                    responseMap != null && responseMap.containsKey("message") ? (String) responseMap.get("message") : "加入租户失败"
            );
        } catch (Exception e) {
            log.error("加入租户异常，异常信息: {}", e.getMessage(), e);
            return ResponseDTO.error(RAGFlowApiConstants.ERROR_CODE_COMMON, "加入租户异常: " + e.getMessage());
        }
    }
}
